
<template>
  <el-row>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="180px"
    >
      <el-form-item
        label="调度模版"
        prop="jobTemplateId"
      >
        <el-select
          v-model="form.jobTemplateId"
          placeholder="请选择调度模版"
          @change="templateChangeHandle"
        >
          <el-option
            v-for="item in templateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item
        label="执行器"
        prop="jobGroup"
      >
        <el-select
          v-model="form.jobGroup"
          placeholder="请选择执行器"
        >
          <el-option
            v-for="item in actuators"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-popover
          placement="top-start"
          title="调度信息"
          trigger="click"
        >
          <el-table :data="actuatorsRecord.filter(item => item.id === form.jobGroup)">
            <el-table-column width="100" property="title" label="执行器名称"/>
            <el-table-column width="160" property="appname" label="appName"/>
            <el-table-column width="180" property="addressList" label="机器地址"/>
          </el-table>
          <el-button slot="reference" round style="margin-left: 6px" type="primary">
            点击查看执行器详情
          </el-button>
        </el-popover>
      </el-form-item>
      <el-form-item
        label="执行器路由策略"
        prop="executorRouteStrategy"
      >
        <el-select
          v-model="form.executorRouteStrategy"
          placeholder="请选择"
        >
          <el-option
            v-for="item in actutorRouteStrategy"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="阻塞处理策略"
        prop="executorBlockStrategy"
      >
        <el-select
          v-model="form.executorBlockStrategy"
          placeholder="请选择"
        >
          <el-option
            v-for="item in actutorBlockStrategy"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item
        label="失败重试次数"
        prop="executorFailRetryCount"
      >
        <el-input-number
          v-model="form.executorFailRetryCount"
          :min="0"
          :max="100"
        />
      </el-form-item>
      <el-form-item
        label="超时时间（分钟）RON"
        prop="executorTimeout"
      >
        <el-input-number
          v-model="form.executorTimeout"
          :min="0"
          :max="100"
        />
      </el-form-item>
      <el-form-item
        label="CRON"
        prop="scheduleConf"
      >
        <el-input v-model="form.scheduleConf" style="width: 180px;margin-right: 6px"/>
        <el-button
          round
          icon="el-icon-edit"
          @click="cronVisible = true"
        />
      </el-form-item>

      <el-popover
        placement="right-end"
        title="下次触发时间"
        width="250"
        trigger="click"
      >
        <div>
          <p v-for="item in nextTriggerTimeList" :key="item">
            {{ item }}
          </p>
        </div>
        <el-button
          slot="reference"
          type="primary"
          round
          @click="getNextTriggerHandle"
        >
          点击查看下次触发时间
        </el-button>
      </el-popover>

      <el-form-item>
        <el-button
          type="primary"
          @click="submitHandler()"
        >
          保存
        </el-button>
        <el-button @click="$emit('onCancel')">
          取消
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      title="配置cron"
      :visible="cronVisible"
      width="60%"
      :modal="false"
      :before-close="() => { cronVisible = false }"
    >
      <CronGenerator :cron-express-props="form.jobCron" @saveCronExpress="onCronExpressChange"/>
      <el-row style="margin-top: 10px">
        <el-button type="primary" @click="saveCronHandle">
          保存
        </el-button>
        <el-button @click="cronVisible = false">
          取消
        </el-button>
      </el-row>
    </el-dialog>
  </el-row>
</template>

<script>
import BaseEditForm from '@/views/common/mixins/BaseEditForm'
import { addSchedule } from '@/api/workDevelopment/index'
import { findAllActuator } from '@/api/dispatchTemplate/index'
import CronGenerator from '@/components/CronGenerator/index'
import { queryFn, nextTriggerTime } from '@/api/dispatchTemplate/index'
// import DispatchConfig from './queryComponents/dispatchConfig.vue'

export default {
  components: { CronGenerator },
  mixins: [BaseEditForm],
  props: {
    records: {
      required: false,
      type: Object,
      default: () => { }
    }
  },
  data() {
    const initRules = () => {
      const isEmpty = (rule, value, callback) => {
        if (value.split(' ').join('').length === 0) {
          callback(new Error('输入变量不可为空'))
        } else {
          callback()
        }
      }
      return {
        // jobTemplateId: [
        //   {
        //     required: true,
        //     message: '请选择模板',
        //     trigger: 'blur'
        //   },
        // ],
        executorFailRetryCount: [
          {
            required: true,
            message: '请输入失败重试次数',
            trigger: 'blur'
          },
        ],
        executorTimeout: [
          {
            required: true,
            message: '请输入超时时间',
            trigger: 'blur'
          },
        ],
        scheduleConf: [
          {
            required: true,
            message: '请填写CRON表达式',
            trigger: 'blur'
          },
        ],
        executorTable: [],
        jobDesc: [
          {
            required: true,
            message: '请输入新增模板名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: 'blur'
          },
          { validator: isEmpty, trigger: 'blur' }
        ]
      }
    }
    return {
      templates: [],
      cronVisible: false,
      finalCronStr: '',
      templateOptions: [],
      actuators: [],
      actuatorsRecord: [],
      nextTriggerTimeList: [],
      actutorRouteStrategy: [
        { label: '随机', value: 'RANDOM' },
        { label: '第一个', value: 'FIRST' },
        { label: '最后一个', value: 'LAST' },
        { label: '轮询', value: 'ROUND' },
        { label: '一致性HASH', value: 'CONSISTENT_HASH' },
        { label: '最不经常使用', value: 'LEAST_RECENTLY_USED' },
        { label: '最近最久未使用', value: 'LEAST_FREQUENTLY_USED' }
      ],
      actutorBlockStrategy: [
        { label: '单机串行', value: 'SERIAL_EXECUTION' },
        { label: '丢弃后调度', value: 'DISCARD_LATER' },
        { label: '覆盖之前调度', value: 'COVER_EARLY' }
      ],
      form: {
        jobTemplateId: null,
        executorBlockStrategy: 'DISCARD_LATER',
        executorFailRetryCount: 3,
        executorTimeout: 3,
        scheduleConf: null
      },
      rules: initRules()
    }
  },
  watch: {
    records: {
      immediate: true,
      deep: true,
      handler(val) {
        if(val && val.xxlJobInfo) {
          this.form.jobTemplateId = val.xxlJobTemplateId ? val.xxlJobTemplateId + '' : null
          this.form.executorFailRetryCount = val.xxlJobInfo.executorFailRetryCount
          this.form.executorTimeout = val.xxlJobInfo.executorTimeout
          this.form.scheduleConf = val.xxlJobInfo.scheduleConf
        }
      }
    }
  },
  mounted() {
    console.log('获取到调度模版123213213', this.records)
    findAllActuator().then((data) => {
      this.actuatorsRecord = data
      this.actuators = data.map(item => ({
        label: item.title,
        value: item.id
      }))
    })

    queryFn({
      page: 1,
      pageSize: 10000,
      filters: {},
      sorts: []
    }).then((data) => {
      this.templateOptions = data.list.map((item) => ({
        label: item.jobDesc,
        value: item.id,
        jobCron: item.jobCron,
        executorTimeout: item.executorTimeout,
        executorFailRetryCount: item.executorFailRetryCount
      }))
    })
  },
  methods: {
    templateChangeHandle(value) {
      if(!value) {
        return;
      }
      let currentTemplate = this.templateOptions.find((item)=> {
        return item.value == value;
      })
      this.form.scheduleConf = currentTemplate.jobCron;
      this.form.executorTimeout = currentTemplate.executorTimeout;
      this.form.executorFailRetryCount = currentTemplate.executorFailRetryCount;
    },
    onCronExpressChange(value) {
      this.finalCronStr = value
    },
    saveCronHandle() {
      this.form.scheduleConf = this.finalCronStr
      this.cronVisible = false
    },
    async getNextTriggerHandle() {
      if(!this.form.scheduleConf) {
        this.$message.error('请先配置CRON表达式')
        return;
      }
      const res = await nextTriggerTime({
        scheduleConf: this.form.scheduleConf
        // id: this.form.jobTemplateId ? this.form.jobTemplateId : 0
      })
      this.nextTriggerTimeList = res || ['暂无数据']
    },
    async submitHandler() {
      this.$refs.form.validate((valid) => {
        if(valid) {
          const params = {
            jobName: this.records.jobName,
            taskType: this.records.taskType,
            taskScheduleType: this.records.taskScheduleType,
            dinkyTaskId: this.records.dinkyTaskId,
            jobInfoId: this.records.jobInfoId,
            executorHandler: this.records.executorHandler,
            dirId: this.records.id,
          }
          addSchedule({
            taskId: this.records.id,
            ...params,
            ...this.form
            // jobName: 'zhouw-test1122-batch111',
            // taskType: 'FlinkSQL',
            // jobGroup: 3,
            // jobTemplateId: 1,
            // scheduleConf: '0 0 0 * * ? *',
            // taskId: '1606105891081179137',
            // taskScheduleType: 'batch',
            // dinkyTaskId: 65,
            // jobInfoId: 0,
            // executorHandler: 'xxl-job-executor-sample',
            // executorRouteStrategy: 'RANDOM',
            // executorBlockStrategy: 'DISCARD_LATER',
            // executorTimeout: 1,
            // executorFailRetryCount: 1
          }).then(res=> {
            if (res) {
              this.notifySuccess('保存成功！')
              this.$emit('successHandle', res)
            }
          })
        }
      });
    },
    notifySuccess(text) {
      this.$message({
        showClose: true,
        message: text,
        type: 'success'
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
